//
//  TabBarController.swift
//  MSwift
//
//  Created by 马龙波 on 2017/10/27.
//  Copyright © 2017年 马龙波. All rights reserved.
//

import UIKit

class TabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        addChildViewController()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
}

extension TabBarController {
    fileprivate func addChildViewController() {
        setupChildViewController(BoardController(), image: "tab_board", selectImage: "tab_board_sel", htitle: "首页")
        setupChildViewController(MessageController(), image: "tab_message", selectImage: "tab_message_sel", htitle: "消息")
        setupChildViewController(PersonController(), image: "tab_person", selectImage: "tab_person_sel", htitle: "个人中心")
    }
    
    fileprivate func setupChildViewController(_ vc: BaseController, image: String, selectImage: String, htitle: String) {
        let navi = NaviController(rootViewController: vc)
        navi.tabBarItem.image = UIImage(named: image)?.withRenderingMode(.alwaysOriginal)
        navi.tabBarItem.selectedImage = UIImage(named: selectImage)?.withRenderingMode(.alwaysOriginal)
        navi.tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0)
        navi.tabBarItem.title = htitle
        navi.tabBarItem .setTitleTextAttributes([NSAttributedStringKey.foregroundColor as NSAttributedStringKey : UIColor.gray], for: .normal)
        navi.tabBarItem .setTitleTextAttributes([NSAttributedStringKey.foregroundColor as NSAttributedStringKey : kRGB(20, g: 186, b: 200)], for: .selected)
        self.addChildViewController(navi)
    }
}

//MARK： 点击动画
extension TabBarController: UITabBarControllerDelegate {
    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        tabBarButtonClick(tabBarButton: getTabBarButton())
    }
    
    private func getTabBarButton() -> UIControl {
        var tabBarButtons: [UIControl] = [UIControl]()
        
        for tabBarButton in self.tabBar.subviews {
            if tabBarButton.isKind(of: NSClassFromString("UITabBarButton") as! UIView.Type) {
                tabBarButtons.append(tabBarButton as! UIControl)
            }
        }
        return tabBarButtons[self.selectedIndex]
    }
    
    private func tabBarButtonClick(tabBarButton: UIControl) {
        for imageView in tabBarButton.subviews {
            if imageView.isKind(of: NSClassFromString("UITabBarSwappableImageView") as! UIView.Type) {
                let animation = CAKeyframeAnimation(keyPath: "transform.scale")
                animation.values = [1.0, 1.1, 0.9, 1.1]
                animation.duration = 0.3
                animation.calculationMode = kCAAnimationCubic
                imageView.layer.add(animation, forKey: nil)
            }
        }
    }
}
